//
//  UserView.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI

struct UserView: View {
    @StateObject private var viewModel = UserViewModel()
    @StateObject private var appState = AppState()
    @State private var showLoginSheet = false
    @State private var showRegisterSheet = false
    @State private var showSettingsSheet = false
    
    // 处理设置按钮点击
    func handleUserSetting() {
        // 只有登录状态才跳转到设置页面
        if viewModel.isLogin {
            if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
               let rootViewController = windowScene.windows.first?.rootViewController {
                // 创建SettingsView，SettingsView内部已有NavigationView和返回按钮
                let appState = AppState()
                let view = SettingsView()
                    .environmentObject(appState)
                let settingsView = UIHostingController(rootView: view)
                settingsView.modalPresentationStyle = .fullScreen
                rootViewController.present(settingsView, animated: true, completion: nil)
            }
        }
        // 未登录状态不做任何处理
    }
    
    var body: some View {
        ZStack(alignment: .top) {
            // 背景颜色延伸到顶部
            LinearGradient(
                colors: [ThemeHelper.shared.getColor(), Color("f5f5f5")],
                startPoint: .top,
                endPoint: .bottom
            )
            .frame(maxHeight: .infinity)
            .edgesIgnoringSafeArea(.top)
            
            ScrollView {
                VStack(spacing: 0) {

                    // 用户信息卡片
                    UserInfoCardView(
                        userInfo: viewModel.userInfo,
                        isLogin: viewModel.isLogin,
                        onLoginTap: {
                            // 使用全屏方式展示登录页面
                            if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                               let rootViewController = windowScene.windows.first?.rootViewController {
                                let loginVC = UIHostingController(rootView: LoginView())
                                loginVC.modalPresentationStyle = .fullScreen
                                rootViewController.present(loginVC, animated: true, completion: nil)
                            }
                        }
                    )
                    .padding(.top, 50) // 增加向上的距离，避免被状态栏遮挡
                    
                    // VIP会员卡片
                    //if viewModel.userInfo?.paidMemberPaidEntrance == 1 {
                        VIPCardView(viewModel: viewModel)
                            .padding(.horizontal, 16)
                            .padding(.top, 28)
                   // }
                    
                    // 订单管理
                    OrderSectionView()
                        .padding(.horizontal, 16)
                        .padding(.top, 0)
                    
                    // 其他功能
                    OtherFunctionView(userViewModel: viewModel)
                        .environmentObject(appState)
                        .padding(.horizontal, 16)
                        .padding(.top, 16)
                    
                    // 底部间距
                    Spacer(minLength: 100)
                }
            }
        }
        .navigationBarHidden(true)
        .ignoresSafeArea(.all, edges: .top)
        .onAppear {
            Task {
                await viewModel.loadUserInfo()
            }
        }
    }
}


struct ServiceCenterMenuItem: Identifiable {
    let id: Int
    let name: String
    let pic: String
    let url: String
    let wap_url: String
    let info: String
}

// MARK: - 用户信息卡片
struct UserInfoCardView: View {
    let userInfo: UserInfo?
    let isLogin: Bool
    let onLoginTap: () -> Void
    
    var body: some View {
        ZStack {
            // 背景渐变
            LinearGradient(
                colors: [ThemeHelper.shared.getColor(), Color("f5f5f5")],
                startPoint: .top,
                endPoint: .bottom
            )
            .edgesIgnoringSafeArea(.top)
            
            
            VStack(spacing: 16) {
                // 用户基本信息
                HStack {
                    VStack(alignment: .leading, spacing: 8) {
                        HStack {
                            // 头像
                            AsyncImage(url: URL(string: userInfo?.fullAvatarUrl ?? "https://shopgo.ttxcx.net/crmebimage/presets/morenT.png")) { image in
                                image
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                            } placeholder: {
                                Image(systemName: "person.circle.fill")
                                    .foregroundColor(.white.opacity(0.8))
                            }
                            .frame(width: 60, height: 60)
                            .clipShape(Circle())
                            
                            VStack(alignment: .leading, spacing: 4) {
                                if isLogin, let userInfo = userInfo {
                                    HStack {
                                        Text(userInfo.nickname ?? "用户")
                                            .font(.headline)
                                            .fontWeight(.semibold)
                                            .foregroundColor(.white)
                                        
                                        if let isPromoter = userInfo.isPromoter, isPromoter {
                                            Image(systemName: "crown.fill")
                                                .foregroundColor(.yellow)
                                                .font(.caption)
                                        }
                                    }
                                    
                                    if let phone = userInfo.phone {
                                        Text(phone)
                                            .font(.caption)
                                            .foregroundColor(.white.opacity(0.8))
                                    }
                                } else {
                                    Button("请点击登录") {
                                        onLoginTap()
                                    }
                                    .font(.headline)
                                    .foregroundColor(.white)
                                    .padding(.vertical, 4)
                                    .padding(.horizontal, 12)
                                    .background(Color.white.opacity(0.2))
                                    .cornerRadius(8)
                                }
                            }
                            
                            Spacer()
                            
                            // 设置按钮
                            Button(action: {
                                // 使用外部的handleUserSetting函数
                                UserView().handleUserSetting()
                            }) {
                                Image(systemName: "gearshape")
                                    .foregroundColor(.white)
                                    .font(.title2)
                            }
                        }
                    }
                }
                
                // 用户数据统计
                HStack(spacing: 0) {
                    UserStatItemView(
                        title: "积分",
                        value: isLogin && userInfo != nil ? "\(userInfo!.integral ?? 0)" : "0"
                    )
                    
 
                    
                    UserStatItemView(
                        title: "优惠券",
                        value: isLogin && userInfo != nil ? "\(userInfo!.couponCount ?? 0)" : "0"
                    )

                    
                    UserStatItemView(
                        title: "收藏",
                        value: isLogin && userInfo != nil ? "\(userInfo!.collectCount ?? 0)" : "0"
                    )
                    
     
                    
                    UserStatItemView(
                        title: "浏览记录",
                        value: isLogin && userInfo != nil ? "\(userInfo!.browseNum ?? 0)" : "0"
                    )
                    

                }
                .padding(.horizontal, 16)
                .padding(.vertical, 8)

            }
            .padding(.horizontal, 20)
            .padding(.top, 20)
            .padding(.bottom, 0)
        }
        .frame(height: isLogin ? 180 : 120)
    }
 }


// MARK: - 用户统计项
struct UserStatItemView: View {
    let title: String
    let value: String
    
    var body: some View {
        VStack(spacing: 4) {
            Text(value)
                .font(.system(size: 18))
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            Text(title)
                .font(.system(size: 14))
                .foregroundColor(.white.opacity(0.8))
        }
        .frame(maxWidth: .infinity)
    }
}
// MARK: - VIP会员卡片
struct VIPCardView: View {
    @ObservedObject var viewModel: UserViewModel
    
    var body: some View {
        HStack {
            HStack(spacing: 8) {
                AsyncImage(url: URL(string: "https://shopgo.ttxcx.net/crmebimage/presets/huangguan.png")) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 16, height: 16)
                } placeholder: {
                    Image(systemName: "crown.fill")
                        .foregroundColor(Color(hex: "#FFD89C"))
                        .font(.system(size: 11))
                }
                
                Text("加入SVIP畅享精彩")
                    .font(.system(size: 11))
                    .fontWeight(.medium)
                    .foregroundColor(Color(hex: "#FFD89C"))
            }
            
            Spacer()
            
            HStack(spacing: 4) {
                Text(viewModel.userInfo?.isPaidMember == true ? "去查看" : "去开通")
                    .font(.system(size: 11))
                    .foregroundColor(Color(hex: "#FFD89C"))
                
                Image(systemName: "chevron.right")
                    .font(.system(size: 11))
                    .foregroundColor(Color(hex: "#FFD89C"))
            }
        }
        .padding(.vertical, 12)
        .padding(.horizontal, 16)
        .frame(height: 47)
        .background(
            AsyncImage(url: URL(string: "https://shopgo.ttxcx.net/crmebimage/presets/cardbj.png")) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
            } placeholder: {
                LinearGradient(
                    colors: [Color.purple.opacity(0.8), Color.blue.opacity(0.6)],
                    startPoint: .leading,
                    endPoint: .trailing
                )
            }
        )
        .cornerRadius(12, corners: [.topLeft, .topRight])
    }
}

struct ServiceMenuSectionView: View {
    @EnvironmentObject var appState: AppState
    @ObservedObject var userViewModel: UserViewModel
    @State private var menuItems: [ServiceCenterMenuItem] = []
    @State private var isLoading: Bool = false
    @State private var errorMessage: String? = nil
    
    init(userViewModel: UserViewModel) {
        self.userViewModel = userViewModel
    }
    
    var body: some View {
        VStack(spacing: 16) {
            HStack {
                 Text("我的服务")
                    .font(.headline)
                    .fontWeight(.semibold)
                
                Spacer()
            }
            
            if isLoading {
                ProgressView()
                    .frame(maxWidth: .infinity, minHeight: 100)
            } else if let error = errorMessage {
                VStack {
                    Text(error)
                        .foregroundColor(.red)
                    Button("重试") {
                        Task {
                            await fetchUserCenterMenu()
                        }
                    }
                    .padding()
                }
                .frame(maxWidth: .infinity, minHeight: 100)
            } else {
                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: 4), spacing: 20) {
                    ForEach(menuItems) { item in
                        ServiceMenuItem(item: item)
                            .onTapGesture {
                                handleMenuItemTap(item)
                            }
                    }
                }
            }
        }
        .padding(16)
        .background(Color.white)
        .cornerRadius(12)
        .onAppear {
            Task {
                await fetchUserCenterMenu()
            }
        }
    }
    
    func fetchUserCenterMenu() async {
        isLoading = true
        errorMessage = nil
        do {
            let response = try await APIService.shared.fetchUserCenterMenu()
            // 检查响应状态码
            if response.code == 200, let menuData = response.data {
                // 直接使用CenterMenuData中的centerMenu数组
                let items = menuData.centerMenu.map { item in
                    return ServiceCenterMenuItem(
                        id: item.id,
                        name: item.name,
                        pic: item.pic,
                        url: item.url,
                        wap_url: item.wap_url,
                        info: item.info ?? ""
                    )
                }
                // 更新UI
                self.menuItems = items
                self.isLoading = false
            } else {
                throw NSError(domain: "APIError", code: 0, userInfo: [NSLocalizedDescriptionKey: "API响应状态码错误: \(response.code)"])
            }
        } catch {
            self.errorMessage = "获取菜单失败: \(error.localizedDescription)"
            self.isLoading = false
            print("获取用户中心菜单出错: \(error.localizedDescription)")
        }
    }
    
    func handleMenuItemTap(_ item: ServiceCenterMenuItem) {
        // 严格检查用户是否登录 - 同时检查 token 和 ViewModel 的登录状态
        guard let token = UserDefaults.standard.string(forKey: APIConfig.tokenName),
              !token.isEmpty,
              userViewModel.isLogin else {
            print("用户未登录，无法访问该页面")
            return
        }
        
        // 获取根视图控制器用于显示新页面
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let rootViewController = windowScene.windows.first?.rootViewController else {
            return
        }
        
        // 提取URL的基础路径（去掉查询参数）
        let baseUrl = extractBaseUrl(from: item.url)
        
        // 根据URL导航到相应页面
        switch baseUrl {
        case "/pages/users/user_info/index":
            // UserInfoView 内部已有返回按钮，需要 NavigationView 才能显示
            let appState = AppState()
            let view = NavigationView {
                UserInfoView()
                    .environmentObject(appState)
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/merchant/user_integral/index":
            let view = NavigationView {
                UserIntegralView()
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button(action: {
                                rootViewController.dismiss(animated: true)
                            }) {
                                Image(systemName: "chevron.left")
                                    .foregroundColor(.primary)
                            }
                        }
                    }
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/users/user_money/index":
            // UserMoneyView 内部已有返回按钮，但需要 NavigationView 才能显示
            let appState = AppState()
            let view = NavigationView {
                UserMoneyView()
                    .environmentObject(appState)
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/merchant/user_sgin/index":
            let appState = AppState()
            let view = NavigationView {
                UserSignView()
                    .environmentObject(appState)
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button(action: {
                                rootViewController.dismiss(animated: true)
                            }) {
                                Image(systemName: "chevron.left")
                                    .foregroundColor(.white)
                                    .font(.system(size: 18, weight: .medium))
                                    .padding(8)
                                    .background(Color.black.opacity(0.3))
                                    .clipShape(Circle())
                            }
                        }
                    }
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/goods/user_merchant_collection/index":
            // UserCollectionView 需要包装在 NavigationView 中才能显示返回按钮
            let appState = AppState()
            let view = NavigationView {
                UserCollectionView()
                    .environmentObject(appState)
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/address/user_address_list/index":
            let appState = AppState()
            let view = NavigationView {
                UserAddressView()
                    .environmentObject(appState)
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/users/user_spread_user/index":
            // UserSpreadView 内部已有返回按钮，需要 NavigationView 才能显示
            let appState = AppState()
            let view = NavigationView {
                UserSpreadView()
                    .environmentObject(appState)
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/users/settled/index":
            // MerchantSettledView 内部已有返回按钮，需要 NavigationView 才能显示
            let appState = AppState()
            let view = NavigationView {
                MerchantSettledView()
                    .environmentObject(appState)
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/goods/order_list/index":
            // 解析URL参数
            var status: Int = -1
            var secondType: Int = 0
            
            if let urlComponents = URLComponents(string: "https://example.com\(item.url)") {
                if let statusParam = urlComponents.queryItems?.first(where: { $0.name == "status" }),
                   let statusValue = statusParam.value {
                    status = Int(statusValue) ?? -1
                }
                if let secondTypeParam = urlComponents.queryItems?.first(where: { $0.name == "secondType" }),
                   let secondTypeValue = secondTypeParam.value {
                    secondType = Int(secondTypeValue) ?? 0
                }
            }
            
            let orderListView = UIHostingController(
                rootView: OrderListView(status: status, secondType: secondType)
            )
            orderListView.modalPresentationStyle = .fullScreen
            rootViewController.present(orderListView, animated: true)
            
        case "/pages/goods/order_details/index":
            // 解析URL参数
            var orderNo: String = ""
            
            if let urlComponents = URLComponents(string: "https://example.com\(item.url)") {
                if let orderNoParam = urlComponents.queryItems?.first(where: { $0.name == "orderNo" }),
                   let orderNoValue = orderNoParam.value {
                    orderNo = orderNoValue
                }
            }
            
            if !orderNo.isEmpty {
                let orderDetailView = UIHostingController(
                    rootView: OrderDetailView(orderNo: orderNo)
                )
                orderDetailView.modalPresentationStyle = .fullScreen
                rootViewController.present(orderDetailView, animated: true)
            }
            
        case "/pages/goods/user_grade/index":
            let view = NavigationView {
                UserGradeView()
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button(action: {
                                rootViewController.dismiss(animated: true)
                            }) {
                                Image(systemName: "chevron.left")
                                    .foregroundColor(.primary)
                            }
                        }
                    }
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/users/user_coupon/index":
            let appState = AppState()
            let view = NavigationView {
                UserCouponView()
                    .environmentObject(appState)
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button(action: {
                                rootViewController.dismiss(animated: true)
                            }) {
                                Image(systemName: "chevron.left")
                                    .foregroundColor(.primary)
                            }
                        }
                    }
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        case "/pages/activity/couponList/index":
            let appState = AppState()
            let view = NavigationView {
                CouponListView()
                    .environmentObject(appState)
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button(action: {
                                rootViewController.dismiss(animated: true)
                            }) {
                                Image(systemName: "chevron.left")
                                    .foregroundColor(.primary)
                            }
                        }
                    }
            }
            let hostingController = UIHostingController(rootView: view)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
            
        default:
            print("未知页面URL: \(item.url)")
        }
    }
    
    // MARK: - 提取URL基础路径（去掉查询参数）
    private func extractBaseUrl(from urlString: String) -> String {
        // 如果包含查询参数（?），只取前面的路径部分
        if let questionMarkIndex = urlString.firstIndex(of: "?") {
            return String(urlString[..<questionMarkIndex])
        }
        // 如果包含 #，也只取前面的路径部分
        if let hashIndex = urlString.firstIndex(of: "#") {
            return String(urlString[..<hashIndex])
        }
        return urlString
    }
}

struct ServiceMenuItem: View {
    let item: ServiceCenterMenuItem
    
    var body: some View {
        VStack(spacing: 8) {
            AsyncImage(url: URL(string: item.pic.trimmingCharacters(in: .whitespaces))) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 40, height: 40)
                    .cornerRadius(8)
            } placeholder: {
                Image(systemName: "questionmark.circle")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 40, height: 40)
                    .foregroundColor(.gray)
            }
            
            Text(item.name)
                            .font(.system(size: 11))
                            .foregroundColor(.primary)
                            .lineLimit(1)
                            .fixedSize(horizontal: false, vertical: true)
                            .multilineTextAlignment(.center)
        }
    }
}

// MARK: - 订单管理区域
struct OrderSectionView: View {
    // 与uniapp版本保持一致的orderMenu结构
    let orderItems = [
        ("待付款", "zf", "/pages/goods/order_list/index?status=0", 0),
        ("待发货", "ff", "/pages/goods/order_list/index?status=1", 0),
        ("待使用", "sy", "/pages/goods/order_list/index?status=3", 0),
        ("待收货", "shuohuo", "/pages/goods/order_list/index?status=4", 0),
        ("待评价", "pj", "/pages/goods/evaluation_list/index", 0),
        ("售后/退款", "sh", "/pages/goods/user_return_list/index", 0)
    ]
    
    var body: some View {
        VStack(spacing: 16) {
            HStack {
                Text("订单中心")
                    .font(.headline)
                    .fontWeight(.semibold)
                
                Spacer()
                
                Button("查看全部") {
                    handleOrderNavigation(url: "/pages/goods/order_list/index?status=-1")
                }
                .font(.caption)
                .foregroundColor(.gray)
            }
            
            HStack(spacing: 0) {
                ForEach(orderItems, id: \.0) { item in
                    Button(action: {
                        handleOrderNavigation(url: item.2)
                    }) {
                        VStack(spacing: 4) {
                            ZStack {
                               
                                Image(item.1)
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                                    .frame(width: 24, height: 24)
                                    
                                // 添加num-wrapper显示数量
                                if item.3 > 0 {
                                    ZStack {
                                        Circle()
                                            .fill(Color.red)
                                            .frame(width: 16, height: 16)
                                        
                                        Text("\(item.3)")
                                            .font(.system(size: 10))
                                            .foregroundColor(.white)
                                    }
                                    .offset(x: 15, y: -15)
                                }
                            }
                            
                            Text(item.0)
                                .font(.system(size: 10))
                                .foregroundColor(.primary)
                                .lineLimit(2)
                                .multilineTextAlignment(.center)
                                .frame(width: 50)
                        }
                        .frame(maxWidth: .infinity)
                    }
                }
            }
        }
        .padding(16)
        .background(Color.white)
        .cornerRadius(12, corners: [.bottomLeft, .bottomRight])
    }
    
    private func handleOrderNavigation(url: String) {
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let rootViewController = windowScene.windows.first?.rootViewController {
            // 解析URL参数
            var status: Int = -1
            var secondType: Int = 0
            
            if let urlComponents = URLComponents(string: "https://example.com\(url)") {
                if let statusParam = urlComponents.queryItems?.first(where: { $0.name == "status" }),
                   let statusValue = statusParam.value {
                    status = Int(statusValue) ?? -1
                }
                if let secondTypeParam = urlComponents.queryItems?.first(where: { $0.name == "secondType" }),
                   let secondTypeValue = secondTypeParam.value {
                    secondType = Int(secondTypeValue) ?? 0
                }
            }
            
            let orderListView = UIHostingController(
                rootView: OrderListView(status: status, secondType: secondType)
            )
            orderListView.modalPresentationStyle = .fullScreen
            rootViewController.present(orderListView, animated: true)
        }
    }
}

// MARK: - 其他功能区域
struct OtherFunctionView: View {
    @EnvironmentObject var appState: AppState
    @ObservedObject var userViewModel: UserViewModel
    
    init(userViewModel: UserViewModel) {
        self.userViewModel = userViewModel
    }
    
    var body: some View {
        ServiceMenuSectionView(userViewModel: userViewModel)
            .environmentObject(appState)
    }
}


struct UserView_Previews: PreviewProvider {
    static var previews: some View {
        UserView()
    }
}
